"""
查询/NAS/CAPFS/data/vdn/vdn_deploy_new/metadata/reload/livets.meta文件实时状态，
具体包括：atime、ctime、mtime
然后：
1.与当前时间进行对比。
如果api获取的atime/ctime/mtime大于当前时间，现象为livets.meta出现未来时间，出现错误，返回1
2.与上一次查询api查询结果进行对比。
如果查询本次api获取的atime/ctime/mtime小于上一次查询时间，现象为livets.meta返回到过去时间，出现错误，返回2
3.正常情况下，查询获得的atime/ctime/mtime应大于或等于上一次查询时间，并且小于或等于当前时间，返回：0

实现思路：
将每次查询的atime与当前时间进行比较，然后与上一次查询的atime值进行比较，然后将本次查询的atime值写入last_atime.txt文件，下一次查询后会把本次atime值覆盖，保持last_atime.txt中记录的始终是最新获取的atime值。
ctime/mtime值查询过程类似。
每次查询后，都将atime/ctime/mtime和now_time写入日志

重要输出参数解释
total           --  查询出的告警总数
recovery_time   --  告警恢复时间
alarm_level     --  critical（紧急）、major（重要）、minor（一般）、warning（提示）、self_define（自定义）
alarm_time      --  告警产生时间
alarm_content   --  告警内容
alarm_status    --  un_recovery（未恢复）, auto_recovery（已恢复）, user_confirm（已确认）
alarm_source    --  告警源
"""

import requests
import json
import re
import datetime
import os


# 将api获取到的string格式的时间转换为float格式的timestamp
def timestring_to_timestamp(timestring):
    time_format = '%Y-%m-%d %H:%M:%S'  # 根据此格式来解析时间字符串为time()对象
    # 字符串先转成datetime.datetime对象，再转成timestamp
    dt = datetime.datetime.strptime(timestring, time_format)
    timestamp_value = dt.timestamp()

    return timestamp_value


def get_h3c_dir_stat_data():
    # 拼接成登陆url
    base_url = "http://地址"
    request_url = "/api/v1/auth/login"
    url = base_url + request_url

    # 登陆用户名、密码
    data = {"username": "xx", "password": "xx"}

    # 登录请求
    res = requests.post(url=url, data=json.dumps(data), headers={'content-type': "application/json"})

    # 获取响应头信息
    # print(res.headers)
    set_cookie = res.headers.get('Set-Cookie')
    text_set_cookie = re.split('[;,]', set_cookie)

    # 从响应头信息中提取后面访问需要的cookie_value和x_xsrf_token_value
    xsrf_token_value = text_set_cookie[3].strip()
    cookie_value = text_set_cookie[0] + ';' + xsrf_token_value
    x_xsrf_token_value = re.split('=', xsrf_token_value)[1]

    # 获取集群ID
    cluster_id_api_url = "/api/v3/plat/cluster"
    cluster_id_url = base_url + cluster_id_api_url
    cluster_res = requests.get(
        url=cluster_id_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': x_xsrf_token_value,
            'Cookie': cookie_value,
        })

    cluster_data = cluster_res.json()
    cluster_id = cluster_data['data']['id']

    # 生成请求URL
    cluster_dir_stat_1 = "/api/v3/onestor/"
    cluster_dir_stat_2 = "/filestorage/dir/stat"
    cluster_dir_stat_url = base_url + cluster_dir_stat_1 + cluster_id + cluster_dir_stat_2
    # print(cluster_dir_stat_url)

    # 请求参数
    request_data = {
        "path": "/vdn/vdn_deploy_new/metadata/reload/livets.meta",
        "type": "file"
    }

    # 发送POST请求，得到返回数据
    cluster_dir_stat_res = requests.post(
        url=cluster_dir_stat_url,
        data=json.dumps(request_data),
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': x_xsrf_token_value,
            'Cookie': cookie_value,
        })
    cluster_dir_stat_data = cluster_dir_stat_res.json()

    # 获取当前时间，类型为datetime.datetime,格式 2023-10-31 17:49:54.878532
    now = datetime.datetime.now()
    # 将当前时间转换为timestamp类型，float格式
    now_float = now.timestamp()

    # 获取atime/ctime/mtime的timestamp，格式float
    atime_string = cluster_dir_stat_data['data']['atime']
    atime_float = timestring_to_timestamp(atime_string)

    ctime_string = cluster_dir_stat_data['data']['ctime']
    ctime_float = timestring_to_timestamp(ctime_string)

    mtime_string = cluster_dir_stat_data['data']['mtime']
    mtime_float = timestring_to_timestamp(mtime_string)

    # last_atime_txt_flag用于判断是否存在last_atime.txt文件。如果不存在，last_atime_txt_flag为false，新建last_atime.txt文件并写入0，用于比较api最新读取的atime和上一次api读取的atime。ctime/mtime类似
    last_atime_txt_flag = os.path.exists("/var/log/h3c/last_atime.txt")
    if last_atime_txt_flag is False:
        f_last_atime_txt = open("/var/log/h3c/last_atime.txt", "w", encoding="UTF-8")
        f_last_atime_txt.write('0')
        f_last_atime_txt.close()

    last_ctime_txt_flag = os.path.exists("/var/log/h3c/last_ctime.txt")
    if last_ctime_txt_flag is False:
        f_last_ctime_txt = open("/var/log/h3c/last_ctime.txt", "w", encoding="UTF-8")
        f_last_ctime_txt.write('0')
        f_last_ctime_txt.close()

    last_mtime_txt_flag = os.path.exists("/var/log/h3c/last_mtime.txt")
    if last_mtime_txt_flag is False:
        f_last_mtime_txt = open("/var/log/h3c/last_mtime.txt", "w", encoding="UTF-8")
        f_last_mtime_txt.write('0')
        f_last_mtime_txt.close()
    # 读取last_atime.txt/last_ctime.txt/last_mtime.txt记载的上一次api调用得到的atime/ctime/mtime值
    f_last_atime = open("/var/log/h3c/last_atime.txt", "r", encoding="UTF-8")
    last_atime_string = f_last_atime.readline()
    last_atime = float(last_atime_string)
    f_last_atime.close()

    f_last_ctime = open("/var/log/h3c/last_ctime.txt", "r", encoding="UTF-8")
    last_ctime_string = f_last_ctime.readline()
    last_ctime = float(last_ctime_string)
    f_last_ctime.close()

    f_last_mtime = open("/var/log/h3c/last_mtime.txt", "r", encoding="UTF-8")
    last_mtime_string = f_last_mtime.readline()
    last_mtime = float(last_mtime_string)
    f_last_mtime.close()

    # 如果正常，返回0；如果获取的atime/ctime/mtime是未来时间，出现错误，返回1；如果最新获取的atime/ctime/mtime比上一次时间小，出现错误，返回2
    flag = 0
    if atime_float > now_float or ctime_float > now_float or mtime_float > now_float:
        flag = 1
    if last_atime > atime_float or last_ctime > ctime_float or last_mtime > mtime_float:
        flag = 2

    # 将最新调用api读取的atime/ctime/mtime值写入last_atime.txt/last_ctime.txt/last_mtime.txt，用于下一次比较判断
    f_last_atime = open("/var/log/h3c/last_atime.txt", "w", encoding="UTF-8")
    f_last_atime.write(str(atime_float))
    f_last_atime.close()

    f_last_ctime = open("/var/log/h3c/last_ctime.txt", "w", encoding="UTF-8")
    f_last_ctime.write(str(ctime_float))
    f_last_ctime.close()

    f_last_mtime = open("/var/log/h3c/last_mtime.txt", "w", encoding="UTF-8")
    f_last_mtime.write(str(mtime_float))
    f_last_mtime.close()

    # 记录日志，将atime/ctime/mtime和now_time写入日志
    # print("atime:" + atime_string + ",ctime:" + ctime_string + ",mtime:" + mtime_string + ",now_time:" + str(now))
    f_log = open("/var/log/h3c/livets.meta.log", "a", encoding="UTF-8")
    f_log.write("atime:" + atime_string + ",ctime:" + ctime_string + ",mtime:" + mtime_string + ",now_time:" + str(now) + "\n")
    f_log.close()

    # logout登出
    logout_api_url = "/api/v1/auth/logout"
    logout_url = base_url + logout_api_url
    logout_res = requests.get(
        url=logout_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': x_xsrf_token_value,
            'Cookie': cookie_value,
        })
    # return cluster_dir_stat_data['data']
    return flag


if __name__ == '__main__':
    alarm_message = get_h3c_dir_stat_data()
    print(alarm_message)